use strict;
use warnings;

use Test::More 'no_plan';

use Person;
use Country;

my $au = Country->new( 'name' => 'Australia' );
$au->load();
is( $au->id, 'AU', "Country Australia loaded" );

my $sg = Country->new( 'name' => 'Singapore' );
$sg->load();
is( $sg->id, 'SG', "Country Singapore loaded" );

my $p = Person->new( 'id' => 1 );
my $rv = $p->load( 'speculative' => 1 );

if ($rv) {
    ok( $p->id, "Person " . $p->name . " loaded" );
}
else {
    $p = Person->new(
        'name'             => 'Woei Shyang',
        'family_name'      => 'Siaw',
        'birth_date'       => '06/08/1981',
        'gender'           => 'M',
        'birth_country_id' => $sg->id
    );
    $p->save();
    ok( $p->id, "Person " . $p->name . " saved" );
} ## end else [ if ($rv)

# Person relationships
is( $p->birth_country->id, "SG", 'Person->birth_country relationship' );

$p->phones( { 'number' => '04025526642', 'type' => 'Mobile', 'country_id' => $au->id } );
$p->save();

is( count_phones($p), 1, "Phone saved" );

my $phone = $p->phones->[0];

$p->phones( $p->phones, { 'number' => '62764491', 'type' => 'Home', 'country_id' => $sg->id } );
$p->save();
is( count_phones($p), 2, "Second phone saved" );

$p->emails( { 'address' => 'test' . time . '@woeishyang.com', 'type' => 'Home' } );
$p->save();

is( count_emails($p), 1, "Email saved" );

$p->addresses(
    {   'address_1'  => '181 Grote Street',
        'city'       => 'Adelaide',
        'state'      => 'SA',
        'postcode'   => '5000',
        'country_id' => $au->id,
        'phones'     => { 'number' => '0883323906', 'type' => 'Home', 'country_id' => $au->id }
    }
);
$p->save();

is( count_phones($p), 2, "Person still has same number of phones" );
is( count_addresses($p), 1, "Address saved" );

my $address = $p->addresses->[0];
$p->phones( $p->phones, $address->phones );
$p->save();

is( count_phones($p), 3, "Person now has 3 numbers" );

my @phones = $p->phones;
foreach my $cur_phone (@phones) {
    test_phone( { 'phone' => $cur_phone } );
}

$p->set_phones();
$p->save();

$p->emails([]);
$p->save();

is( count_phones($p), 3, "Person still has 3 numbers" );

sub test_phone {
    my $params  = shift || {};
    my $phone   = $params->{'phone'};
    my $country = $phone->country;

    my $calling_prefix = $country->calling_prefix;

    ok( substr( $phone->number, 0, length( $country->calling_prefix ) ) eq $country->calling_prefix,
        "Country formatting for " . $country->name . " works" );
} ## end sub test_phone

sub count_addresses {
    my $person = shift;
    my @addresses = $person->addresses;
    return scalar(@addresses);
}

sub count_emails {
    my $person = shift;
    my @emails = $person->emails;
    return scalar(@emails);
}

sub count_phones {
    my $person = shift;
    my @phones = $person->phones;
    return scalar(@phones);
}
